﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Jabr.Logic.Roster;

namespace Jabr.GUI.Forms
{
    public partial class AccountAdd : Form
    {
        private AbstractAccount m_acc;
        private bool m_accept;

        public AccountAdd()
        {
            InitializeComponent();

            this.m_accept = false;
            foreach (Type t in Assembly.GetAssembly(typeof(AbstractAccount)).GetTypes())
            {
                if (t.IsSubclassOf(typeof(AbstractAccount)))
                {
                    AbstractAccount aat = (AbstractAccount)t.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
                    AccountBindingSource.Add(aat);
                }
            }
        }

        public AbstractAccount AccountCreated
        {
            get
            {
                return this.m_acc;
            }
        }

        private void RegisterNew_CheckedChanged(object sender, EventArgs e)
        {
            this.ConfirmLabel.Visible = this.ConfirmValue.Visible = this.RegisterNew.Checked;
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.m_accept = false;
            this.Close();
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            this.m_accept = true;
            this.Close();
        }

        private void AccountAdd_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.m_accept && e.CloseReason == CloseReason.UserClosing)
            {
                if (string.IsNullOrEmpty(this.NameValue.Text) || string.IsNullOrEmpty(this.UserValue.Text) || string.IsNullOrEmpty(this.PasswordValue.Text))
                {
                    MessageBox.Show("All fields are required", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                if (this.RegisterNew.Checked && this.PasswordValue.Text != this.ConfirmValue.Text)
                {
                    MessageBox.Show("Passwords must match", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                AbstractAccount aa = (AbstractAccount)this.TypeValue.SelectedItem;
                aa.Username = this.NameValue.Text;
                aa.UserID = this.UserValue.Text;
                aa.Password = this.PasswordValue.Text;
                aa.New = this.RegisterNew.Checked;
                this.m_acc = aa;
            }
        }
    }
}
